import protobuf from "./api_protobuf"
import consoles from "./api_console"
import cWebSocket from "../../SuperMgr/cWebSocket"
export default class api_websocket  {
    private static pb:protobuf = null;
    private ws:WebSocket       = null;
    private md:cWebSocket      = null;
    constructor(md:cWebSocket){
        this.md = md;
    }
    public connect(){
        let pd = api_websocket.pb;
        let md = this.md;
        let fc = function(){
            let ws = new WebSocket(md.wshost());
            this.ws = ws;
            ws.binaryType = "arraybuffer";
            ws.onopen = function (event:Event) {
                md.onopen();
            };
            ws.onmessage = function (event:MessageEvent) {
                let pd = api_websocket.pb;
                let msg = pd.decode_message(event.data)
                md.onmessage(msg);
            };
            ws.onerror = function (event:Event) {
                md.onclose();
            };
            ws.onclose = function (event:CloseEvent) {
                md.onclose();
            };
        }.bind(this)
        if(null !== pd){
            fc()
        }
        else{
            api_websocket.pb=new protobuf(fc)
        }
    }
    public sendmail(name:string,cmds:string[],data:msgBody){
        if(this.readyState()){
            let blob = api_websocket.pb.encode_message(name,cmds,data);
            this.ws.send(blob)
        }
        else{
            consoles.msgLog("websocket is not open");
        }
    }

    public readyState():boolean{
       return this.ws.readyState === WebSocket.OPEN 
    }
}